<?php

namespace addons\shopro\controller;

use addons\shopro\exception\Exception;
use addons\shopro\model\Store as ModelStore;
use addons\shopro\model\User;
use addons\shopro\model\UserStore;

class Store extends Base
{

    protected $noNeedLogin = ['allList'];
    protected $noNeedRight = ['*'];


    public function index()
    {
        $user = User::info();
        $userStore = UserStore::where('user_id', $user->id)->select();
        $store_id_arr = array_column($userStore, 'store_id');

        $stores = [];
        if ($store_id_arr) {
            $stores = ModelStore::show()->where('id', 'in', $store_id_arr)->select();
        }
        
        $this->success('获取门店列表', $stores);
    }

    public function allList()
    {
        $param = $this->request->param();

        $page = $param['page'];
        $limit = $param['limit'];
        $current_lat = $param['lat']; // 纬度
        $current_lng = $param['lng']; //经度

        $pre = ($page - 1) * $limit;
        $sql = "SELECT *,(6371 * ACOS(
                                COS(RADIANS($current_lat)) * COS(RADIANS(latitude)) * COS(
                                    RADIANS(longitude) - RADIANS($current_lng)
                                ) + SIN(RADIANS($current_lat)) * SIN(RADIANS(latitude))
                            )
                        ) AS distance
                    FROM
                        fa_shopro_store
                    ORDER BY
                        distance
                    LIMIT $pre, $limit";

        $res = UserStore::query($sql);
        if(!empty($res)){
            foreach ($res as $key=>$val){
                if($current_lat <= 0 || $current_lng <= 0){
                    $res[$key]['distance'] = "未知";
                }else{
                    $res[$key]['distance'] = round($res[$key]['distance'],2);
                }
            }
        }

        $this->success('获取门店列表', $res);
    }
}
